package com.eds.service;

import com.eds.dto.CourseImageMessage;
import com.eds.mapper.CourseMapper;
import com.eds.mapper.OssImageMapper;
import com.pojo.Course;
import com.pojo.OssImage;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Date;

@Service
@Slf4j
public class DeadLetterService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private OssImageMapper ossImageMapper;

    /**
     * 处理死信队列消息
     */
    @RabbitListener(queues = "course.image.dead.queue")
    public void processDeadLetter(CourseImageMessage message, Channel channel, Message amqpMessage) throws IOException {
        try {
            log.warn("处理死信队列消息: courseId={}, relationType={}", message.getCourseId(), message.getRelationType());

            // 重试处理
            retryProcessImage(message);

            // 确认消息处理完成
            channel.basicAck(amqpMessage.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("处理死信队列消息失败", e);
            // 拒绝消息，不重新入队
            channel.basicReject(amqpMessage.getMessageProperties().getDeliveryTag(), false);

            // 记录失败信息到数据库或日志系统
            recordFailedMessage(message);
        }
    }

    /**
     * 重试处理图片消息
     */
    private void retryProcessImage(CourseImageMessage message) throws Exception {
        // 1. 保存图片信息到OSS表
        OssImage ossImage = new OssImage();
        ossImage.setUrl(message.getImageUrl());
        ossImage.setRelationType(message.getRelationType());
        ossImage.setUserId(message.getUserId());
        ossImage.setCourseId(message.getCourseId());
        ossImage.setDescription("课程内容图片" + message.getImageIndex() + "(重试)");
        ossImage.setUploadTime(new Date());
        ossImageMapper.insert(ossImage);

        // 2. 更新课程表中对应的图片字段
        Course course = courseMapper.selectById(message.getCourseId());
        if (course != null) {
            String fieldName = message.getImageIndex() == 0 ? "title" : "content" + message.getImageIndex();
            Field field = Course.class.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(course, message.getImageUrl());
            courseMapper.updateById(course);
        }
    }

    /**
     * 记录失败消息
     */
    private void recordFailedMessage(CourseImageMessage message) {
        // 可以保存到数据库或日志系统，以便后续人工处理
        log.error("图片处理最终失败，需人工干预: courseId={}, imageUrl={}",
                message.getCourseId(), message.getImageUrl());
    }
}